import 'dart:async';

import 'package:ai_data_capture/req/api/ConfigApi.dart';
import 'package:ai_data_capture/req/api/CurrentConfigApi.dart';
import 'package:ai_data_capture/req/exp.dart';
import 'package:ai_data_capture/req/network_service.dart';
import 'package:ai_data_capture/util/toast_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import 'state.dart';

class MainLogic extends GetxController {
  final MainState state = MainState();
  bool is_continue_to_get = true;

  var controller = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    init();
    controller.text = NetworkService.BASE_URL;
    startGetLoop();
  }

  void startGetLoop() async {
    while (true) {
      if (!is_continue_to_get) {
        break;
      }
      await continue_get();
      await Future.delayed(const Duration(seconds: 3));
    }
  }

  Future<void> init() async {
    state.status.value = await ConfigApi.getStatus();

    state.fList.clear();
    state.fList.addAll(await ConfigApi.getFunctions());

    state.currentConfig.value = await CurrentConfigApi.getCurrentConfig();
  }

  @override
  void onClose() {
    super.onClose();
    is_continue_to_get = false;
  }

  Future continue_get() async {
    try {
      var res = await ConfigApi.getStatus();
      state.status.value = res;
      state.currentConfig.value = await CurrentConfigApi.getCurrentConfig();
    } catch (e) {
      if (e is ApiException) {
        print(e.message);
      }
      print(e);
    }
  }

  void setup() {
    if (controller.text.isEmpty) {
      showToast("请输入链接");
      return;
    }
    NetworkService.BASE_URL = controller.text;
    showToast("已设置");
    init();
  }
}
